import React, { Component } from 'react';
import autoBind from 'react-autobind';
import { Checkbox, Icon, Stepper, Modal } from 'antd-mobile';

// style
import styles from './index.css';
import IconfontStyle from '../../../assets/iconfont/iconfont.css';

//widget
import InputNumber from '../../Common/InputNumber'

class BuyCarBodyItem extends Component {
	constructor(props) {
        super(props)
        autoBind(this)

        
        this.state = this.getStateFromProps(props)
    }
    componentWillReceiveProps(nextProps) {
        if(nextProps.checkAll != this.props.checkAll
            || nextProps.store != this.props.store) {
            // this.setState(this.getStateFromProps(nextProps))
            this.setState(this.getStateFromProps(nextProps), this.getExtendStore)
        }   
    }
    getStateFromProps(props) {
    	const { store } = props
        let initState = {
        	stepValue: 1,
            checkItemAll: props.checkAll || false,
        	goodsStep: {},
        	goodsCheckbox: {}
        }
        store.goodsList.map((good, kk) => {
        	initState.goodsStep[good.cartId] = good.goodsNumber || 1;
        	initState.goodsCheckbox[good.cartId] = props.checkAll || false
        })
        return initState
    }
    onStepChange(cartId, kk, stepValue) {
        const { store, checkAll, dispatch } = this.props

        dispatch({
            type: 'buycar/modifyCartNumber',
            payload: {
                cartId: cartId,
                goodsNumber: stepValue
            }
        })
    	this.setState({
    		goodsStep: {
    			...this.state.goodsStep,
    			[cartId]: stepValue
    		}
    	}, this.getExtendStore)
    }
    onItemCheckbox(kk, e) {
    	this.setState({
    		goodsCheckbox: {
    			...this.state.goodsCheckbox,
    			[kk]: e.target.checked
    		}
    	}, () => {
            this.checkIsCheckAll()
            this.getExtendStore()
        })
    }
    onCarBodyItemChange(e) {
    	let temp = this.state.goodsCheckbox

    	for(let i in temp) {
    		temp[i] = e.target.checked
    	}
    	this.setState({
    		goodsCheckbox: temp,
            checkItemAll: e.target.checked
    	}, this.getExtendStore)
    }
    getExtendStore() {
        const { mergeStore, store } = this.props
        let fakeStore = JSON.parse(JSON.stringify(store))
        fakeStore.isChecked = this.state.checkItemAll
        fakeStore.goodsList.map((good, kk) => {
            good.number = this.state.goodsStep[good.cartId]
            good.checked = this.state.goodsCheckbox[good.cartId]
        })
        mergeStore && mergeStore(fakeStore)
    }
    checkIsCheckAll() {
        let isCheckAll = true
        for(let k in this.state.goodsCheckbox) {
            if(!this.state.goodsCheckbox[k]) {
                isCheckAll = false
            }
        }
        this.setState({
            checkItemAll: isCheckAll
        })
    }
    onDeleteCart(cartId) {
        const { dispatch, store } = this.props

        let cartIds = (() => {
            let cartIdArr = []
            store.goodsList && store.goodsList.map((good, ii) => {
                if(this.state.goodsCheckbox[good.cartId]) {
                    cartIdArr.push(good.cartId)
                }
            })
            return cartIdArr.join(',')
        })() 

        Modal.alert('确定要从购物车删除吗?', '', [
          { text: '取消', onPress: () => {
            console.log('delete cancel.')
          }},
          { text: '确定', onPress: () => {
            dispatch({
                type: 'buycar/deleteCart',
                payload: cartIds
            })
          } },
        ])
    }
	render() {
		const { store, checkAll } = this.props
	 	return (
	 		<div className="buy-car-body-item">
	 			<div className={styles["buy-car-body-item-title"]}>
	 				<Checkbox
                        checked={this.state.checkItemAll}
                        onChange={this.onCarBodyItemChange}>
	 					<span style={{marginLeft: '0.16rem', verticalAlign: 'middle', fontSize: '0.28rem', color: 'rgb(66,62,62)'}}>{store.brandName}</span>
	 				</Checkbox>
	 				<i onClick={this.onDeleteCart} className={`${IconfontStyle['meyley-icon']} ${IconfontStyle['meyley-icon-delete']}`} style={{float: 'right', fontSize: '0.4rem'}}/>
	 			</div>
	 			{
	 				store.goodsList.map((good, k) => {
	 					return (<div key={k} className={styles["buy-car-body-item-goods"]}>

	 							<div className={styles["buy-car-body-item-goods-left"]} style={{flex: 5}}>
		 							<Checkbox className={styles["buy-car-body-item-goods-left-checkbox"]} onChange={this.onItemCheckbox.bind(this, good.cartId)} checked={this.state.goodsCheckbox[good.cartId] || false} />
		 							<div  className={styles["buy-car-body-item-goods-left-img"]}  style={{textAlign: 'center'}}>
		 								<img src={good.goodsThumb} className={styles["buy-car-body-item-goods-img"]} />
		 							</div>
		 						</div>
	 							<div className={styles["goods-info"]}>
                                    <div className={styles['goods-info-name']}>{good.goodsName}</div>
	 								<div className={styles['goods-info-des']}>{good.goodsAttrs}</div>
	 								<div className={styles["goods-info-bottom"]}>
	 									<span style={{color: 'rgb(255, 0, 82)', fontSize: '0.28rem'}}>￥{good.goodsPrice}</span>
	 									<Stepper
								            className="production-detail-stepper"
								            showNumber min={1} value={this.state.goodsStep[good.cartId] || 1} onChange={this.onStepChange.bind(this, good.cartId, good.goodsId)}
								         />
	 								</div>
	 							</div>
	 						</div>)
	 				})
	 			}
	 			
	 		</div>
	  	);
	}
};

BuyCarBodyItem.propTypes = {
};

export default BuyCarBodyItem
